package at.tugraz.akm.forume.extras;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.util.Log;

public abstract class Utils {

	public static boolean isLogged(Context context) {
		if (!MySharedPreferences.getString(context,
				MySharedPreferences.USERNAME).equalsIgnoreCase(
				MySharedPreferences.UNDEFINED)
				&& !MySharedPreferences.getString(context,
						MySharedPreferences.PASSWORD).equalsIgnoreCase(
						MySharedPreferences.UNDEFINED)
				&& !MySharedPreferences.getString(context,
						MySharedPreferences.USER_ID).equalsIgnoreCase(
						MySharedPreferences.UNDEFINED)) {
			return true;
		} else {
			return false;
		}
	}

	public static String convertURL(String str) {
		String url = null;
		try {
			url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
					.replace(",", "%2c").replace("(", "%28")
					.replace(")", "%29").replace("!", "%21")
					.replace("=", "%3D").replace("<", "%3C")
					.replace(">", "%3E").replace("#", "%23")
					.replace("$", "%24").replace("'", "%27")
					.replace("*", "%2A").replace("-", "%2D")
					.replace(".", "%2E").replace("/", "%2F")
					.replace(":", "%3A").replace(";", "%3B")
					.replace("?", "%3F").replace("@", "%40")
					.replace("[", "%5B").replace("\\", "%5C")
					.replace("]", "%5D").replace("_", "%5F")
					.replace("`", "%60").replace("{", "%7B")
					.replace("|", "%7C").replace("}", "%7D"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return url;
	}

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException ioe) {
			Log.e("convertStreamToString()", ioe.getLocalizedMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.e("convertStreamToString() - finally",
						e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}

	public static final String md5(final String s) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++) {
				String h = Integer.toHexString(0xFF & messageDigest[i]);
				while (h.length() < 2)
					h = "0" + h;
				hexString.append(h);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}
}
